package com.warmguard.core.config.redis;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.warmguard.core.enums.ResultCodeEnum;
import com.warmguard.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: RedisUtil
 * PackageName: com.innovation.warm.util
 * Description:
 *
 * @Author: 32782
 * @Date: 2024/11/14 下午5:32
 * @Version: 1.0
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }


    public void set(String key, Object value, Integer time, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, time, timeUnit);
    }
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void deleteObject(String key) {
        redisTemplate.delete(key);
    }

    public <T> T get(String key, Class<T> tClass) {
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            throw new ServiceException(ResultCodeEnum.LOGIN_FAILED);
        }
        if (o instanceof JSONObject jsonObject) {
            return JSON.to(tClass, jsonObject);
        }else {
         throw new ServiceException(ResultCodeEnum.CONVERSION_ERROR);
        }
    }
}
